<template>
  <div class="app-container calendar-list-container">
      <!-- 搜索框，对工单单号,工单单别进行搜索 -->
    <div class="filter-container">
        <el-radio v-model="radio" label="1" @change="radioChange">
            <el-input
            clearable
            v-model="listQuery.workOrderNo"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工单单号"
            :disabled="radio != '1'"
            ></el-input>
            <el-input
                clearable
                v-model="listQuery.orderType"
                style="width: 150px;margin-right:15px;margin-top:7px"
                class="filter-item"
                placeholder="请输入工单单别"
                :disabled="radio != '1'"
            ></el-input>
        </el-radio>

        <el-radio v-model="radio" label="2" @change="radioChange">
            <!-- style="width: 150px;margin-right:15px;margin-top:7px" -->
            <el-input
            clearable
            v-model="orderPlanNo"
            style="margin-right: 15px;margin-top:7px"
            :style="{ width: inputWid(orderPlanNo) }"
            class="filter-item"
            placeholder="请输入计划批号"
            :disabled="radio != '2'"
            ></el-input>
        </el-radio>
        <el-button class="filter-item" style="margin-top:7px" type="primary" v-waves icon="el-icon-search" @click="findValidTechnologyNo">查询</el-button>
        <!-- <el-button
              type="button"
              class="el-button el-button--warning filter-item"
              @click="loading = false"
            >
              取消</el-button> -->
        <el-button class="filter-item" style="margin-top:7px" :loading="btnLoading" type="primary" v-waves @click="dialogFormVisible = true">查询结果</el-button>
        <div>
          <el-radio v-model="radio" label="3" @change="radioChange">
              <!-- style="width: 150px;margin-right:15px;margin-top:7px" -->
              <template v-for="(item,index) in orderPlanNoList">
              <el-input
              :key="index"
              v-model="item.orderPlanNo"
              clearable
              style="margin-right:7px;margin-top:7px"
              :style="{ width: inputWid(orderPlanNo) }"
              class="filter-item"
              placeholder="批量添加计划批号"
              :disabled="radio != '3'"
              ></el-input>
      </template>
          </el-radio>
          <el-button circle style="margin-top:7px" type="success" v-waves icon="el-icon-plus" @click="addList"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="deleteList"></el-button>
        </div>

    </div>

    <div class="btn-button" v-if="orderList3.length">
        <el-button type="warning" @click="showModifyTime = true">批量修改</el-button>
        <el-button type="primary" :loading="formLoading" @click="intercept('form')">确定提交</el-button>
        <!-- <el-button type="primary" @click="resetForm('form')">重置</el-button> -->
    </div>
    <!-- 工单信息列表 -->
    <el-collapse v-model="activeName" accordion>
     <el-collapse-item :title="'工单：' + item.orderType + '-' + item.workOrderNo" :name="index" v-for="(item,index) in orderList3" :key="index">
        <el-form ref="form" :model="item" label-width="120px" size="medium">
            <el-form-item label="工单单号" prop="workOrderNo" >
                <el-input v-model="item.workOrderNo" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="工单单别" prop="orderType">
                <el-input v-model="item.orderType" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="任务令" prop="po">
                <el-input v-model="item.po" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="工段编号" prop="sectionNo" required>
                <el-input v-model="item.sectionNo" placeholder="工段编号" @blur="checkSectionExist(item,index)" style="width:300px" />
                <!-- <el-select v-model="item.sectionNo" placeholder="请选择工段编号" @focus="getSection" style="width:300px">
                    <el-option :value="item" :label="item" v-for="(item,index) in sectionList" :key="index"/>
                </el-select> -->
            </el-form-item>
            <el-form-item label="排产时间" prop="planTime" required>
                <el-date-picker :clearable="false" v-model="item.planTime"  format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width:300px" />
            </el-form-item>
            <el-form-item label="排产数量" prop="planNumber" required>
                <el-input v-model="item.planNumber" style="width:300px" disabled/>
            </el-form-item>
            <el-form-item label="剩余可排产数量" prop="surplusAmount">
                <el-input v-model="item.surplusAmount" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计产量" prop="estimateYield">
                <el-input v-model="item.estimateYield" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM时间" prop="bomTimeStr">
                <el-input v-model="item.bomTimeStr" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM版本" prop="bomVersion">
                <el-input v-model="item.bomVersion" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="非标信息" prop="notStandard">
                <el-input v-model="item.notStandard" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="免检信息" prop="exemption">
                <el-input v-model="item.exemption" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计开始时间" prop="estimateStartTimeStr">
                <el-date-picker
                v-model="item.estimateStartTimeStr"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择预计开始时间"
                style="width:300px"
                :clearable="false">
                </el-date-picker>
                <!-- <el-input v-model="item.estimateStartTimeStr" style="width:300px"  disabled/> -->
            </el-form-item>
            <el-form-item label="预计结束时间" prop="estimateEndTimeStr" required>
                <el-date-picker
                v-model="item.estimateEndTimeStr"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择预计结束时间"
                style="width:300px"
                :clearable="false">
                </el-date-picker>
                <!-- <el-input v-model="item.estimateEndTimeStr" style="width:300px" disabled/> -->
            </el-form-item>
            <el-form-item label="工作中心" prop="workCenter">
                <el-input v-model="item.workCenter" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品名称" prop="produceName">
                <el-input v-model="item.produceName" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品规格" prop="specification">
                <el-input v-model="item.specification" style="width:300px" disabled />
            </el-form-item>
        </el-form>
     </el-collapse-item>
    </el-collapse>

    <!-- 选择工单 -->
    <el-dialog title="批量添加工单" :visible.sync="dialogFormVisible" width="900px">
        <div style="text-align: center;" class="edit_dev">
            <el-button type="warning" size="mini" @click="ifTechnology">工艺未录入</el-button>
        </div>
         <div style="text-align: center" class="edit_dev">
            <el-transfer
            style="text-align: left; display: inline-block"
            v-model="orderList4"
            filterable
            :titles="['未选中', '选中']"
            :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
            }"
            @change="handleChange"
            :data="orderList2"
            target-order="unshift">
                <span slot-scope="{ option }">{{ option.label }}</span>
                <el-select slot="left-footer" v-model="department" placeholder="工作中心" clearable @change="filterWorkcenter" @clear="clearWorkcenter" style="width: 100px;margin-left: 4px"  >
                    <el-option :value="item" :label="item" v-for="(item,index) in centerList" :key="index"/>
                </el-select>
                <el-cascader class="transfer-footer"  placeholder="单号头" slot="left-footer" style="width: 100px" v-model="filterOrder" :options="optionsOrder" @change="filterOrderList" :props="props" collapse-tags clearable></el-cascader>
            </el-transfer>

            <div v-if="showFilter" class="showFilter">
                <el-checkbox v-model="workCenter1" @change="changeWorkCenter1">焊接车间</el-checkbox>
                <el-checkbox v-model="workCenter2" @change="changeWorkCenter2">喷涂车间</el-checkbox>
            </div>

        </div>
    </el-dialog>


    <!-- 添加失败弹窗，工单工艺未录入 -->
    <el-dialog title="工单工艺未录入列表" :visible.sync="errorTechnologyNoDialog" width="500px">
        <div v-for="(item,index) in errorTechnologyNoList" :key="index">
            <el-divider content-position="left" v-if="item.order.length">工作中心：{{item.workCenter}}</el-divider>
            <div  v-for="(items,index1) in item.order" :key="index1">
                <el-link type="danger" :underline="false">{{items.orderType + '-' + items.workOrderNo}}</el-link>
                <el-link type="danger" :underline="false">{{'，品号：'+items.produceNo}}</el-link>
            </div>
        </div>
        <el-divider></el-divider>
        <div class="errorBtn">
            <el-button type="primary" @click="errorTechnologyNoDialog = false">确定</el-button>
        </div>
    </el-dialog>

    <!-- 上传失败弹窗 -->
    <el-dialog title="添加工单失败列表" :visible.sync="errorDialog" width="500px">
        <div v-for="(item,index) in errorLists" :key="index">
            <el-link :underline="false">{{item.planNo}}:</el-link>
            <el-link :underline="false" type="warning">{{item.errMsg}}</el-link>
        </div>
        <el-divider></el-divider>
        <div class="errorBtn">
            <el-button type="primary" @click="errorSure">确定</el-button>
        </div>
    </el-dialog>

    <!-- 批量修改弹出表单 -->
    <el-dialog title="批量修改" :visible.sync="showModifyTime" width="600px">
    <el-form :model="modifyform">
        <el-form-item label="工作中心" :label-width="formLabelWidth" required>
            <el-select
            clearable
            v-model="modifyform.workCenter"
            placeholder="请选择工作中心"
            style="width:400px"
            >
                <el-option
                :value="item"
                :label="item" v-for="(item,index) in this.workCenterList"
                :key="index"/>
            </el-select>
        </el-form-item>
        <el-form-item label="工段编号" :label-width="formLabelWidth" v-if="modifyform.workCenter && modifyform.workCenter.trim() != '数控车间' && modifyform.workCenter.trim() != '焊喷车间'">
            <el-input v-model="modifyform.sectionNo" placeholder="工段编号" @blur="checkSectionExist1" style="width:400px" />
            <!-- <el-select v-model="modifyform.sectionNo" placeholder="请选择工段编号" @focus="getSection" style="width:400px">
                <el-option :value="item" :label="item" v-for="(item,index) in sectionList" :key="index"/>
            </el-select> -->
        </el-form-item>
        <el-form-item label="排产时间" :label-width="formLabelWidth">
            <el-date-picker
            v-model="modifyform.planTime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择排产时间"
            style="width:400px" />
        </el-form-item>
        <el-form-item label="预计开始时间" :label-width="formLabelWidth">
            <el-date-picker
                v-model="modifyform.estimateStartTimeStr"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择预计开始时间"
                style="width:400px"
                :clearable="false">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="预计结束时间" :label-width="formLabelWidth">
            <el-date-picker
                v-model="modifyform.estimateEndTimeStr"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择预计结束时间"
                style="width:400px"
                :clearable="false">
            </el-date-picker>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showModifyTime = false">取 消</el-button>
      <el-button type="primary" @click="modifyTime">确 定</el-button>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { orderInfo, addOrderPlan, getSectionList,getOrderByNoSK,findValidTechnologyNo } from '../../api/productionPlan'
import { WorkSecExist,checkWorkSecInfo } from '../../api/workSection.js'
import { getProcessList } from '../../api/processRoute'
export default {
    name: 'cncAddplan',
    data() {
        return {
            activeName: '工单列表',
            orderPlanNo: '',            //计划批号
            orderPlanNoList:[{orderPlanNo:''}],         //计划批号列表
            listQuery: {
                workOrderNo: '',						//工单单号
                orderType: ''							//工单单别
            },
            // 产品信息表单，需提交后台
            form: {
                workOrderNo: '',						//工单单号
                orderType: '',							//工单单别
                sectionNo: '',							//工段编号
                planNumber: '',							//排产数量
                planTime: '',							//排产时间
                bomTimeStr: '',							//BOM时间
                bomVersion: '',							//BOM版本
                notStandard: '',						//非标信息
                estimateStartTimeStr: '',				//预计开始时间
                estimateEndTimeStr: '',					//预计结束时间
                estimateYield: '',						//预计产量
                workCenter: '',							//工作中心
                produceName: '',						//产品名称
                specification: '',						//产品规格
                surplusAmount: '',						//剩余可排产数量
                exemption: ''							//免检标志位
            },
            sectionList: null,							//已经录入后台的工段编号
            orderList2: [],     //穿梭框左侧列表
            dialogFormVisible: false,
            orderList4: [],     //穿梭框右侧列表
            orderList3: [],     //折叠列表.length == 穿梭框右侧列表.length
            orderList1: [],      //全部工单
            errorLists: [],       //排产失败列表
            errorDialog: false,
            radio: '2',
            times: 0,               //添加数据请求次数
            modifyform: {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: ''
            },
            showModifyTime: false,
            formLabelWidth: '100px',                    //批量修改时间输入框的长度控制
            btnLoading: false,
            workCenterList: [],
            props: { multiple: true },
            optionsOrder: [
                {
                    value: 20601,
                    label: '20601-环氧板',
                },
                {
                    value: 20602,
                    label: '20602-环氧板',
                },
                {
                    value: 20701,
                    label: '20701-PC板',
                },
                {
                    value: 20702,
                    label: '20702-PC板',
                },
                {
                    value: 20801,
                    label: '20801-PMMA',
                },
                {
                    value: 20901,
                    label: '20901-PA66+GF（25%）',
                },
                {
                    value: 21001,
                    label: '21001-绝缘膜',
                },
                {
                    value: 2110,
                    label: '2110-海绵',
                },
                {
                    value: 21201,
                    label: '21201-隔热棉',
                },
                {
                    value: 20106,
                    label: '20106-铜排',
                },
                {
                    value: 20107,
                    label: '20107-铝排',
                }
            ],
            filterOrder: '',
            formLoading: false,
            department: '',
            centerList: [],
            showFilter: false,           //当选择焊喷车间则显示
            workCenter1: false,
            workCenter2: false,
            errorTechnologyNoList: [],       //工单工艺未录入列表
            errorTechnologyNoDialog: false,
            validTechnologyNoList: []
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        ifTechnology(){
            this.errorTechnologyNoList = [{
                        order: []
                    }]
            this.orderList1.forEach(item => {
                    this.validTechnologyNoList.forEach(elm =>{
                        if(elm.getOrderType.trim() == item.orderType.trim() && elm.getWorkOrderNo.trim() == item.workOrderNo.trim() && !elm.processName){
                            this.errorTechnologyNoList[0].order.push({orderType: item.orderType,workOrderNo: item.workCenter,workOrderNo: elm.getWorkOrderNo.trim(),produceNo: elm.getProduceNo})
                        }
                    })
                })
            this.errorTechnologyNoDialog = true
                    this.orderList4 = []
                    this.orderList3 = []
        },
        filterWorkcenter(e){
            // this.department
            this.orderList3 = []
            this.orderList4 = []
            this.resetModify()
            this.orderList2 = []
            if(this.department){
                let zwarr1 = []
                if(this.filterOrder.length){
                    this.filterOrder.forEach((itemf) => {
                        zwarr1 = zwarr1.concat(this.orderList1.filter(item => item.produceNo.indexOf(itemf)==0 && item.workCenter == this.department))
                    });
                } else {
                    zwarr1 = zwarr1.concat(this.orderList1.filter(item => item.workCenter == this.department))
                }

                zwarr1.forEach((item,index) => {
                    let obj = {}
                    obj.key = index
                    obj.label = item.orderType + '-' + item.workOrderNo
                    this.orderList2.push(obj)
                });
            } else {
                this.clearWorkcenter()
            }
            if(this.department && this.department.trim() == '焊喷车间' ){
                this.showFilter = true
            } else {
                this.showFilter = false
                this.workCenter1 = false
                this.workCenter2 = false
            }
        },
        clearWorkcenter(){
            this.orderList3 = []
            this.orderList4 = []
            this.resetModify()
            this.orderList2 = []
            if(this.filterOrder.length){ return this.filterOrderList() }
            this.orderList1.forEach((item,index) => {
                let obj = {}
                obj.key = index
                obj.label = item.orderType + '-' + item.workOrderNo
                this.orderList2.push(obj)
            });
            this.showFilter = false
            this.workCenter1 = false
            this.workCenter2 = false
        },
        filterOrderList(){
            this.orderList3 = []
            this.orderList4 = []
            this.resetModify()
            this.orderList2 = []
            this.showFilter = false
            this.workCenter1 = false
            this.workCenter2 = false
            if(this.filterOrder.length){
                let zwarr = []
                if(this.department){
                    this.filterOrder.forEach((itemf) => {
                        zwarr1 = zwarr1.concat(this.orderList1.filter(item => item.produceNo.indexOf(itemf)==0 && item.workCenter == this.department))
                    });
                } else {
                    this.filterOrder.forEach((itemf) => {
                        zwarr = zwarr.concat(this.orderList1.filter(item => item.produceNo.indexOf(itemf)==0))
                    });
                }

                // this.orderList2.forEach((item,index) => {
                //     this.filterOrder.forEach((itemf) => {
                //         if(item.produceNo.indexOf(itemf)){
                //             let obj = {}
                //             obj.key = index
                //             obj.label = item.orderType + '-' + item.workOrderNo
                //             zwarr.push(obj)
                //         }
                //     });
                // });
                zwarr.forEach((item,index) => {
                    let obj = {}
                    obj.key = index
                    obj.label = item.orderType + '-' + item.workOrderNo
                    this.orderList2.push(obj)
                });
            } else {
                if(this.department){
                    this.filterWorkcenter()
                } else {
                    this.orderList1.forEach((item,index) => {
                        let obj = {}
                        obj.key = index
                        obj.label = item.orderType + '-' + item.workOrderNo
                        this.orderList2.push(obj)
                    });
                }

            }
        },
        errorSure(){
            this.errorDialog = false
            this.errorLists = []
        },
        // 清空缓存
        radioChange(e){
            console.log(e)
            this.orderList1 = []
            this.orderList2 = []
            this.orderList3 = []
            this.orderList4 = []
            this.errorLists = []
            this.listQuery = {
                workOrderNo: '',
                orderType: ''
            }
            this.orderPlanNo = ''
        },
        // 输入工单单号与工单单别，查询相应的数据
        async handleFilter() {
            let query = {}
            if(this.radio == '1') {
                query.orderType = this.listQuery.orderType
                query.workOrderNo = this.listQuery.workOrderNo
            } else {
                query.orderPlanNo = this.orderPlanNo
            }
            let data = await getOrderByNoSK(query)
            this.btnLoading = false
            if(data.code == '2') return this.$message.error(data.msg)
            this.orderList1 = data.data
            console.log('data',data.data);
            this.orderList1.forEach((item33,index) => {
                item33.estimateStartTimeStr = this.timeformat2(item33.estimateStartTimeStr)
                item33.estimateEndTimeStr = this.timeformat2(item33.estimateEndTimeStr)
            });
            this.dialogFormVisible = true
            let arr = JSON.parse(JSON.stringify(data.data))
            this.orderList2 = []
            this.orderList3 = []
            this.workCenterList = []
            this.showFilter = false
            this.workCenter1 = false
            this.workCenter2 = false
            // item.produceNo.indexOf('20601')==0
            let midworkCenterList1 = []
            arr.forEach((item,index) => {
                let obj = {}
                obj.key = index
                obj.label = item.orderType + '-' + item.workOrderNo
                this.orderList2.push(obj)
                if(item.workCenter) { midworkCenterList1.push(item.workCenter) }
            });
            this.orderList4 = []
            this.filterOrder = ''
            this.department = ''
            // 重置批量修改时间
            this.modifyform = {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: ''
            }
            if(midworkCenterList1.length){
                let set = new Set(midworkCenterList1)
                this.centerList = Array.from(set)
            }
        },
        // 拦截，提示是否确定提交
        intercept(value){
            if(!this.orderList3.length) return this.$message({
                message: '请先选择工单',
                type: 'warning'
             })
            if(this.orderList3.some(item => !item.sectionNo)){
                let workcen = []
                this.orderList3.forEach((item,index) => {
                    if(!item.sectionNo) { workcen.push(item.workCenter) }
                });
                let set = new Set(workcen)
                return this.$message({
                    message: '请先完善'+Array.from(set).join(',')+'工单的信息',
                    type: 'warning'
                 })
            }
            this.$confirm('确定工单信息是否无误', '注意', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.divideDatas()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        // 每条数据请求一次
        divideDatas(){
            for(let i = 0; i < this.orderList3.length; i++){
                for (let j = i + 1; j < this.orderList3.length; j++) {
                    if(this.orderList3[i].orderType == this.orderList3[j].orderType && this.orderList3[i].workOrderNo == this.orderList3[j].workOrderNo){
                        return this.$message.warning('不能有相同的工单！')
                    }
                }
            }       
            for(let i = 0; i <  this.orderList3.length; i++){
                this.orderList3[i].planTime = this.orderList3[i].planTime.split(' ')[0]
                if(this.orderList3[i].estimateEndTimeStr < this.orderList3[i].planTime) {
                    return this.$message.warning(`工单${this.orderList3[i].orderType}-${this.orderList3[i].workOrderNo}结束时间比排产时间早！`)
                }
            }
            this.formLoading = true
            this.errorLists = []
                this.orderList3.forEach((item,index) => {
                    this.onSubmit(item,index)
            });
        },
        // 将工单信息表单提交到后台
        async onSubmit(item,index) {
            let query = Object.assign({},item)
            query.notStandard = (query.notStandard == '标准') ? 'N' : 'Y'
            query.exemption = (query.exemption == '免检') ? '0' : '1'
            query.estimateStartTimeStr = query.estimateStartTimeStr.split('-')[0] + query.estimateStartTimeStr.split('-')[1] + query.estimateStartTimeStr.split('-')[2]
            query.estimateEndTimeStr = query.estimateEndTimeStr.split('-')[0] + query.estimateEndTimeStr.split('-')[1] + query.estimateEndTimeStr.split('-')[2]
            if(item.clientNumber){ query.clientNumber = item.clientNumber.trim() }
            if(item.orderPlanNo){ query.orderPlanNo = item.orderPlanNo.trim() }
           const data = await addOrderPlan(query)
            this.times++
            const errMsg = data.msg
            if(data.code == '1'){
                this.orderList3.forEach((item3,index3) => {
                    if(item3.orderType == item.orderType && item3.workOrderNo == item.workOrderNo) {
                        this.orderList3.splice(index3,1)
                        this.orderList4.splice(index3,1)
                    }
                });
                this.orderList1.forEach((item1,index1) => {
                    if(item1.orderType == item.orderType && item1.workOrderNo == item.workOrderNo) {
                        this.orderList1[index1].surplusAmount = 0
                    }
                });
         	} else {
                let obj = {
                    planNo: item.orderType + '-' + item.workOrderNo,
                    errMsg
                }
              	this.errorLists.push(obj)
            }
            if(this.orderList3.length){
                if(this.errorLists.length){
                    this.errorDialog = true
                }
                this.formLoading = false
            } else {
                // 重置批量修改时间
                this.modifyform = {
                    planTime: '',
                    estimateEndTimeStr: '',
                    estimateStartTimeStr: ''
                }
                this.formLoading = false
                this.$message({
                    message: '添加成功',
                    type: 'success'
                 })
            }
        },
        // 穿梭框选中列表
        handleChange(value, direction, movedKeys) {
          this.workCenterList = []
            console.log('选中列表',value)
            console.log('左侧列表',this.orderList2)
            console.log(value, direction, movedKeys);
            let arr = []
            let midworkCenterList = []
            value.forEach(items => {
                // this.orderList1
                let valueorderType = this.orderList2[items].label.split('-')[0].trim()
                let valueworkOrderNo = this.orderList2[items].label.split('-')[1].trim()
                this.orderList1.forEach((item,index) => {
                    if(valueorderType == item.orderType.trim() && valueworkOrderNo == item.workOrderNo.trim()){
                      // console.log(index,item,item.workCenter.trim(),item.workOrderNo);
                      if(item.orderType != '5102'){
                          if(item.workCenter && item.workCenter.trim() == '数控车间'){ item.sectionNo = '010101' }
                          if(item.workCenter && item.workCenter.trim() == '焊喷车间'){ item.sectionNo = '010201' }
                          if(item.workCenter && item.workCenter.trim() == '喷涂车间'){ item.sectionNo = '020302' }
                        }
                        // item.sectionNo = '010101'
                        item.planNumber = item.surplusAmount
                        item.planTime = this.modifyform.planTime?this.modifyform.planTime:this.timeformat(item.estimateStartTimeStr)
                        item.estimateStartTimeStr = this.modifyform.estimateStartTimeStr?this.modifyform.estimateStartTimeStr:item.estimateStartTimeStr
                        item.estimateEndTimeStr = this.modifyform.estimateEndTimeStr?this.modifyform.estimateEndTimeStr:item.estimateEndTimeStr
                        arr.push(item)
                        if(item.workCenter) { midworkCenterList.push(item.workCenter) }
                        // console.log('1',item.workCenter);
                    }
                })
            });
            console.log('arr',arr);
            for(const item of arr){
                if(item.workCenter){
                    if(item.workCenter.trim() == '装配车间' || item.workCenter.trim() == 'EMS总装车间'){
                        if(!item.clientNumber){
                          this.orderList4 = []
                          this.orderList3 = []
                          return this.$message.error(`${item.orderType}-${item.workOrderNo}工单没有客户品号！`)
                        }
                    }
                }
            }
            const bool1 = arr.some(item => item.orderType === '5102')
            console.log('bool1',bool1);
              for (var i = 0; i < arr.length; i++) {
                if(bool1 && arr[i].orderType !== '5102') {
                  this.orderList4 = []
                  this.orderList3 = []
                  return this.$message.error('单别是5102的不能和别的一起排产!')
                }
              }
            const bool = arr.every(item => item.orderType === '5102')
              if(bool){
                if(this.workCenterList.length === 0){
                  this.workCenterList = ["数控车间","焊接车间","喷涂车间"]
                }
            }else {
              if(midworkCenterList.length){
                console.log('midworkCenterList',midworkCenterList);
                let set = new Set(midworkCenterList)
                const workCenterList = Array.from(set)
                this.workCenterList = workCenterList.filter(item => item.trim() !== '焊喷车间');
                console.log('1212',this.workCenterList);
            }
            }
            arr.forEach(item1 => {
                item1.notStandard = (item1.notStandard == 'N') ? '标准' : '非标'
                item1.exemption = (item1.exemption == '0')  ? '免检' : '非免检'
            });
            // const bool = arr.every(item => item.orderType === '5102')
            // console.log(bool);
            // console.log(this.workCenterList);
            // if(bool){
            //   if(this.workCenterList.length === 0){
            //     this.workCenterList = ["数控车间","焊接车间","喷涂车间"]
            //   }
            // }
            let errorOrder = []
            let errorworkCenter = []
            this.errorTechnologyNoList = []
            arr.forEach(item => {
                if(item.workCenter){ errorworkCenter.push(item.workCenter) }
                // if(this.validTechnologyNoList.some(data => data.getWorkOrderNo.trim() == item.workOrderNo.trim() && data.getOrderType.trim() == item.orderType.trim())){
                //     // errorOrder.push(item)
                //     errorworkCenter.push(item.workCenter)
                // }
            })
            if(errorworkCenter.length){
                let set = new Set(errorworkCenter)
                errorworkCenter = Array.from(set)
                errorworkCenter.forEach((item,index) => {
                    let obj = {
                        workCenter: item,
                        order: []
                    }
                    this.errorTechnologyNoList.push(obj)
                })
                // 选择的列表
                value.forEach(item => {
                    const parts = this.orderList2[item].label.split("-");
                    this.validTechnologyNoList.forEach(elm =>{
                        if(elm.getOrderType.trim() == parts[0].trim() && elm.getWorkOrderNo.trim() == parts[1].trim() && !elm.processName){
                            this.errorTechnologyNoList[0].order.push({orderType: parts[0],workOrderNo: elm.getWorkOrderNo.trim(),produceNo: elm.getProduceNo})
                        }
                    })
                    // errorworkCenter.forEach((items,index) => {
                    //     if(item.workCenter){
                    //         if(item.workCenter.trim() ==  items.trim() && this.validTechnologyNoList.some(data => data.getWorkOrderNo.trim() == item.workOrderNo.trim() && data.getOrderType.trim() == item.orderType.trim() && !data.processName)){
                    //             this.errorTechnologyNoList[index].order.push({orderType: item.orderType,workOrderNo: item.workOrderNo,produceNo: item.produceNo})
                    //         }
                    //     } else { console.log(item) }
                    // })
                })
                // errorOrder.forEach(item => {
                //     errorworkCenter.forEach((items,index) => {
                //         if(item.workCenter.trim() == items.trim()){ this.errorTechnologyNoList[index].order.push({orderType: item.orderType,workOrderNo: item.workOrderNo,produceNo: item.produceNo})}
                //     })
                // })
                let havePt = false
                console.log('validTechnologyNoList',this.validTechnologyNoList);
                this.validTechnologyNoList.forEach((data,index) => {
                    if(arr.some(item => data.getWorkOrderNo.trim() == item.workOrderNo.trim() && data.getOrderType.trim() == item.orderType.trim())){ havePt = true}
                })
                if(this.errorTechnologyNoList.some(data => data.order.length)){
                    console.log('未录入工艺工单',errorOrder)
                    this.errorTechnologyNoDialog = true
                    this.orderList4 = []
                    this.orderList3 = []
                    return
                } else {
                    if(this.workCenter1 || this.workCenter2){
                        arr.forEach(item1 => {
                            if(this.workCenter1){ item1.sectionNo = '010201' }
                            else { item1.sectionNo = '' }
                        });
                    }
                    arr.forEach(async item => {
                        console.log('item',item);
                        if(item.workCenter && item.workCenter.trim() == '焊喷车间'){
                          let query = {
                             technologyNo: item.produceNo,
                             technologyEnd: item.produceNo,
                             page: 1,
                             limit: 1000
                            }
                          const data = await getProcessList(query)
                          if(!data.data.records.length){
                                this.orderList4 = []
                                this.orderList3 = []
                                return this.$message.error('该工单未添加工艺信息!')
                            } else {
                                item.workCenter = data.data.records[0].workCenter
                                this.workCenterList.push(data.data.records[0].workCenter)
                                this.workCenterList = Array.from(new Set(this.workCenterList))
                                if(data.data.records[0].workCenter.trim() == '喷涂车间'){
                                  item.sectionNo = '020302'
                                }
                            }
                          // item.workCenter = '焊接车间'
                          }
                    });
                    this.orderList3 = arr
                }

            } else {
                if(this.workCenter1 || this.workCenter2){
                    arr.forEach(item1 => {
                        if(this.workCenter1){ item1.sectionNo = '010201' }
                        else { item1.sectionNo = '' }
                    });
                }
                this.orderList3 = arr
                console.log('arr',this.orderList3)
            }
        },
        timeformat(val){
            return val + ' ' + '00:00:00'
        },
        timeformat2(val){
            return val.substring(0,4) + '-' + val.substring(4,6) + '-' + val.substring(6,8)
        },
        modifyTime(){
            if(!this.modifyform.workCenter) return this.$message.error('请先选择工作中心!')
            if(this.modifyform.planTime == '' && this.modifyform.estimateEndTimeStr == '' && this.modifyform.estimateStartTimeStr == '' && !this.modifyform.sectionNo){
                this.showModifyTime = false
                return
            }
            console.log('orderList3',this.orderList3);
            this.orderList3.forEach(async item => {
                if(item.workCenter && item.orderType !== '5102') {
                    console.log(5102);
                  // console.log(this.modifyform.workCenter.trim());
                  // console.log(item.workCenter.trim());
                  // console.log(this.modifyform.workCenter.trim() == item.workCenter.trim());
                    if(this.modifyform.workCenter.trim() == item.workCenter.trim()){
                        if(this.modifyform.planTime){item.planTime = this.modifyform.planTime}
                        if(this.modifyform.estimateStartTimeStr){item.estimateStartTimeStr = this.modifyform.estimateStartTimeStr}
                        if(this.modifyform.estimateEndTimeStr){item.estimateEndTimeStr = this.modifyform.estimateEndTimeStr}
                        if(this.modifyform.sectionNo) { item.sectionNo = this.modifyform.sectionNo }
                        this.showModifyTime = false
                    }else{
                        
                      // return this.$message.error('工作中心不一致')
                    }
                } else if(item.orderType == '5102') {
                    console.log(this.modifyform);
                    if(this.modifyform.planTime){item.planTime = this.modifyform.planTime}
                    if(this.modifyform.estimateStartTimeStr){item.estimateStartTimeStr = this.modifyform.estimateStartTimeStr}
                    if(this.modifyform.estimateEndTimeStr){item.estimateEndTimeStr = this.modifyform.estimateEndTimeStr}
                    if(this.modifyform.workCenter) { item.workCenter = this.modifyform.workCenter }
                    if(this.modifyform.workCenter == '数控车间') {
                        item.sectionNo = '010101'
                    } else if(this.modifyform.sectionNo){
                        item.sectionNo = this.modifyform.sectionNo
                    }
                    this.showModifyTime = false
                }
            });
              this.$message.success('操作完成')
              this.resetModify()
              // console.log('处理后',this.orderList3);
        },
        resetModify(){
            this.modifyform = {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: '',
                sectionNo: ''
            }
        },
        // 工段编号sectionNo下拉触发函数
        async getSection() {
            const data = await getSectionList()
            this.sectionList = data.data
        },
        // 对整个表单输入进去清空
        resetForm(formItem) {
          this.$refs[formItem].resetFields()
        },
        changeWorkCenter1(e){
            if(this.workCenter2){ this.workCenter2 = false}
            this.filterHPWorkcenter()
        },
        changeWorkCenter2(e){
            if(this.workCenter1){ this.workCenter1 = false}
            this.filterHPWorkcenter()
        },
        filterHPWorkcenter(){
            if(!this.workCenter1 && !this.workCenter2){
                this.filterWorkcenter()
                return
            }
            let acitveWorkCenter = this.workCenter1?'焊接车间':'喷涂车间'
            this.orderList3 = []
            this.orderList4 = []
            this.resetModify()
            this.orderList2 = []
            if(this.department){
                let zwarr1 = []
                let zwarr2 = []
                if(this.filterOrder.length){
                    this.filterOrder.forEach((itemf) => {
                        zwarr1 = zwarr1.concat(this.orderList1.filter(item => item.produceNo.indexOf(itemf)==0 && item.workCenter == this.department))
                    });
                } else {
                    zwarr1 = zwarr1.concat(this.orderList1.filter(item => item.workCenter == this.department))
                }
                if(!zwarr1.length) return
                zwarr1.forEach((item,index) => {
                    this.validTechnologyNoList.forEach((item1,index1) => {
                        if(item1.workCenter){
                            if(item.orderType.trim() == item1.getOrderType.trim() && item.workOrderNo.trim() == item1.getWorkOrderNo.trim() && item1.workCenter.trim() == acitveWorkCenter){
                                zwarr2.push(item)
                            }
                        }
                    })
                })
                zwarr2.forEach((item,index) => {
                    let obj = {}
                    obj.key = index
                    obj.label = item.orderType + '-' + item.workOrderNo
                    this.orderList2.push(obj)
                });
            } else {
                this.clearWorkcenter()
            }
        },
        // 点击添加list
        addList(){
          if (this.radio === '3') {
            this.orderPlanNoList.push({orderPlanNo:''})
          }
        },
        // 删除list
        deleteList(){
          if (this.radio === '3') {
            if(this.orderPlanNoList.length > 1){
              this.orderPlanNoList.pop()
            }
          }
        },
        async findValidTechnologyNo(){
            if (this.radio == '2' && this.orderPlanNo == '') return this.$message({
                message: '计划批号不能为空',
                type: 'warning'
            })
            if (this.radio == '1') {
                if(this.listQuery.orderType == '' || this.listQuery.workOrderNo == '') return this.$message({
                message: '工单单别或者工单单号不能为空',
                type: 'warning'
                })
            }
            if (this.radio == '3') {
              const bool = this.orderPlanNoList.every(item => item.orderPlanNo)
              if(!bool) return this.$message({
                message: '计划批号不能为空',
                type: 'warning'
              })
              for(let i = 0; i < this.orderPlanNoList.length; i++) {
                for(let j = i + 1; j < this.orderPlanNoList.length; j++){
                  console.log(this.orderPlanNoList[i]);
                    if(this.orderPlanNoList[i].orderPlanNo === this.orderPlanNoList[j].orderPlanNo){
                        return this.$message({
                          message: `计划批号${this.orderPlanNoList[i].orderPlanNo}不能重复`,
                          type: 'warning'
                        })
                    }
                }
              }
            }

            this.btnLoading = true
            if(this.radio == '3'){
              this.handleFilter3()
            }else if(this.radio == '1'){
                this.handleFilter() 
            }else {
                let data = await findValidTechnologyNo({orderPlanNo: this.orderPlanNo})
                console.log('111',data)
                if(data.code == '2') return this.$message.error(data.msg)
                this.validTechnologyNoList = data.data
                this.handleFilter()
            }
        },
      async handleFilter3(){
            this.orderList1 = []
            this.orderList2 = []
            this.orderList3 = []
            this.validTechnologyNoList = []
            let orderArr = []
            // this.orderPlanNoList.forEach(async (item,index) =>{ })
            // let index = 0;
            for(let item of this.orderPlanNoList) {
                // console.log(`Date ${index} Start!`);
                let data = await getOrderByNoSK({orderPlanNo:item.orderPlanNo})
                let data1 = await findValidTechnologyNo({orderPlanNo: item.orderPlanNo})
                // console.log('data1',data1);
                this.validTechnologyNoList.push(...data1.data)
                if(data.data.length === 0) return this.$message.error(item.orderPlanNo + '没查到工单！')
                if(data.code == '2') return this.$message.error(data.msg)
                // console.log( data.data);
                orderArr.push(...data.data);
                this.orderList1.push(...data.data);
                // console.log(`Date ${index} End!`);
                // index++;
            }
            console.log('orderList1',this.orderList1);
            // console.log('orderArr',orderArr);
            // console.log(this.validTechnologyNoList);
            this.btnLoading = false
            this.orderList1.forEach((item33,index) => {
                item33.estimateStartTimeStr = this.timeformat2(item33.estimateStartTimeStr)
                item33.estimateEndTimeStr = this.timeformat2(item33.estimateEndTimeStr)
            });
            this.dialogFormVisible = true
            let arr = JSON.parse(JSON.stringify(orderArr))
            this.orderList2 = []
            this.orderList3 = []
            this.workCenterList = []
            this.showFilter = false
            this.workCenter1 = false
            this.workCenter2 = false
            // item.produceNo.indexOf('20601')==0
            let midworkCenterList1 = []
            arr.forEach((item,index) => {
                let obj = {}
                obj.key = index
                obj.label = item.orderType + '-' + item.workOrderNo
                this.orderList2.push(obj)
                if(item.workCenter) { midworkCenterList1.push(item.workCenter) }
            });
            this.orderList4 = []
            this.filterOrder = ''
            this.department = ''
            // 重置批量修改时间
            this.modifyform = {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: ''
            }
            if(midworkCenterList1.length){
                let set = new Set(midworkCenterList1)
                this.centerList = Array.from(set)
            }
        },
        // 当焦点移开input输入框触发该函数，检查工段编号是否已经注册
        async checkSectionExist(item,index) {
            if(!item.sectionNo) return this.$message.error('工段编号不能为空')
            const data = await checkWorkSecInfo({sectionId: item.sectionNo})
            let errormsg = data.msg
            if(data.code =='500') return
            if(data.code =='1' && data.data.records.length){
                this.$message({
                    type: 'success',
                    message: '工段编号验证通过!'
                })
            } else if(data.code =='1' && !data.data.records.length){
                this.orderList3[index].sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: '工段编号不存在!'
                })
            } else {
                this.orderList3[index].sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: errormsg
                })
            }
        },
        // 当焦点移开input输入框触发该函数，检查工段编号是否已经注册
        async checkSectionExist1() {
            if(!this.modifyform.sectionNo) return this.$message.error('工段编号不能为空')
            const data = await checkWorkSecInfo({sectionId: this.modifyform.sectionNo})
            let errormsg = data.msg
            if(data.code =='500') return
            if(data.code =='1' && data.data.records.length){
                this.$message({
                    type: 'success',
                    message: '工段编号验证通过!'
                })
            } else if(data.code =='1' && !data.data.records.length){
                this.modifyform.sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: '工段编号不存在!'
                })
            } else {
                this.modifyform.sectionNo = ''
                this.$message({
                    type: 'warning',
                    message: errormsg
                })
            }
        },

    }
}
</script>

<style lang="scss" scoped>
/deep/ .el-transfer-panel__body{
    margin-bottom: 40px;
    width: 200px;
}
.btn-button{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
}
 .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
    font-size: 10px;
  }
   .edit_dev >>> .el-transfer-panel {
     width:260px;
     display: flex;
     flex-direction: column;
   }
   /deep/ .el-transfer-panel__footer{
        display: flex;
        align-items: center;
        // margin-left: 10px;
   }
   /deep/ .transfer-footer{
    margin-left: 2px;
   }
   .errorBtn{
    display: flex;
    justify-content: flex-end;
   }
   .showFilter{
    width: 494px;
    margin-top: 10px;
   }
</style>
